﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using CSRedis;
using NetMicro.Cache;

namespace NetMicro.Cache.DelayBus
{
    /// <summary>
    /// 任务池
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public static class JobPool
    {
        /// <summary>
        /// 任务池前缀
        /// </summary>
        private const string _prefix = "delay-queue-jobpool:";




        /// <summary>
        /// 将任务添加进任务池
        /// </summary>
        /// <param name="job"></param>
        /// <returns></returns>
        public static Task<bool> PutJobAsync<T>(this IRedisCache redisCache, T job) where T : EventJob
        {
            //检验jobid是否全局唯一？
            return redisCache.SetAsync($"{_prefix}{job.JobId}", Newtonsoft.Json.JsonConvert.SerializeObject(job));
        }

        /// <summary>
        /// 将任务添加进任务池
        /// </summary>
        /// <param name="job"></param>
        /// <returns></returns>
        public static void PutJob<T>(this CSRedisClientPipe<string> clientPipe, T job) where T : EventJob
        {
            //检验jobid是否全局唯一？
            clientPipe.Set($"{_prefix}{job.JobId}", Newtonsoft.Json.JsonConvert.SerializeObject(job));
        }

        /// <summary>
        /// 获取指定任务数据
        /// </summary>
        /// <param name="jobId"></param>
        /// <returns></returns>
        public static async Task<T> GetJobAsync<T>(this IRedisCache redisCache, string jobId)
        {
            string ret = await redisCache.GetAsync($"{_prefix}{jobId}");
            if (string.IsNullOrWhiteSpace(ret))
            {
                return default(T);
            }
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(ret);
        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="jobId"></param>
        /// <returns></returns>
        public static Task<long> DelJobAsync(this IRedisCache redisCache, string jobId)
        {
            return redisCache.DelAsync(key: $"{_prefix}{jobId}");
        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="jobId"></param>
        /// <returns></returns>
        public static void DelJob(this CSRedisClientPipe<string> clientPipe, string jobId)
        {
            clientPipe.Del($"{_prefix}{jobId}");
        }

    }
}
